import { useState } from 'react';
import { NavBar, SearchBar, Toast } from 'antd-mobile';
import './index.less';
import { useNavigate } from 'react-router-dom';
import { DeleteOutline } from 'antd-mobile-icons';
import { getSearchHistory, setSearchHistory } from '@/utils/storage';

const Search = () => {

  const navigate = useNavigate();
  const [history, setHistory] = useState(getSearchHistory());

  const back = () => {
    // navigate('/home');
    navigate('/');
  };

  const goSearch = (key) => {
    // 去重，新搜索的内容置顶
    // 返回数组中第一次出现给定元素的下标，如果不存在则返回 -1。  ！== -1 说明有
    const index = history.indexOf(key)
    if (index !== -1) {
      history.splice(index, 1)
    }
    history.unshift(key)
    // setHistory(history)
    // 到26行是改变搜索历史
    setSearchHistory(history)
    console.log(key);
    navigate(`/searchlist/goods/list?searchlist=${key}`)
  };

  const clear = () => {
    setHistory([]);
    setSearchHistory([]);
    Toast.show({
      content: 'Clear successful',
      position: 'top',
    });
  }

  return (
    <>
      <div className="searchtop">
        <NavBar backArrow={true} onBack={back}>商品搜索</NavBar>
      </div>

      <div>
        <SearchBar
          placeholder='请输入搜索关键词'
          showCancelButton={() => true}
          onCancel={() => {
            console.log('dianjile');
          }}
          onSearch={(value) => {
            goSearch(value)
          }}
        />
      </div>


      <div class="search-history">
        <div class="title">
          <span>最近搜索</span>
          <van-icon name="delete-o" size="16" />
          <DeleteOutline onClick={() => { clear() }} />
        </div>
        <div className="list">
          {
            history.map((item, index) => {
              return (
                <div key={index} className="list-item" onClick={(item) => { goSearch(item) }}>
                  {item}
                </div>
              )
            })
          }
        </div>
      </div>

    </>
  )
};

export default Search;